<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>C++ Tutorial: Taste of Assembly</title>
  <meta
 content="C++ Tutorial: Taste of Assembly"
 name="description" />
  <meta
 content="C++ Tutorial, Pointers, Assembly, Heap, Stack, Register, ALU, Stack Pointer(sp), Fram Pointer(fp)"
 name="keywords" />
  <meta http-equiv="Content-Type"
 content="text/html; charset=ISO-8859-1" />
  <link type="text/css" rel="stylesheet" href="../images/bogostyleWidePre.css" />
</head>
<body>
<div id="page" align="center">
<div id="content" style="width: 800px;">
<div id="logo">
<div class="whitetitle" style="margin-top: 70px;">bogotobogo </div>
</div>
<div id="topheader">
<div class="headerbodytext" align="left"><br />
<strong>Bogotobogo</strong><br />
contact@bogotobogo.com </div>
<div class="smallgraytext" id="toplinks"><a href="../index.html">Home</a>
| <a href="../sitemap.html">Sitemap</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="menu">
<div class="smallwhitetext" style="padding: 9px;" align="right"><a
 href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">Products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="submenu">
<div class="smallgraytext" style="padding: 9px;" align="right">
<a href="../gif.html">Gif</a> 
|<a href="../java_applet.html">JavaApplet/Web Start</a>
| <a href="../flash.html">Flash</a>
| <a href="../shockwave.html">ShockWave</a>
| <a href="../svg.html">SVG</a>
| <a href="../iPhone.html">iPhone/iPad</a>
| <a href="../android.html">Android</a>
| <a href="../OnHTML5.html">HTML5</a>
| <a href="../Algorithms/algorithms.html">Algorithms</a>
| <a href="../News/NewsMain.html">News</a>
| <a href="../cplusplus/cpptut.html">C++</a>
| <a href="../Java/tutorial/on_java.html">Java</a>
| <a href="../php/phptut.html">PHP</a>
| <a href="../DesignPatterns/introduction.html">Design Patterns</a>
| <a href="../python/pytut.html">Python</a> 
| <a href="../CSharp/.netframework.html">C#</a>
| <a href="../forums.html">Forums</a> 
| <a href="../VisualBasicSQL/introduction.html">Visual Basic</a>
</div>
</div>

<div id="contenttext">
<br />
<!-- Use of this code assumes agreement with the Google Custom Search Terms of Service. -->
<!-- The terms of service are available at http://www.google.com/cse/docs/tos.html -->
<form name="cse" id="searchbox_demo" action="http://www.google.com/cse">
  <input type="hidden" name="cref" value="" />
  <input type="hidden" name="ie" value="utf-8" />
  <input type="hidden" name="hl" value="" />
  <input name="q" type="text" size="40" />
  <input type="submit" name="sa" value="Search" />
</form>
<script type="text/javascript" src="http://www.google.com/cse/tools/onthefly?form=searchbox_demo&lang="></script>


<br />
<div style="padding: 10px;"><span class="titletext">C++ Tutorial -   Taste of Assembly</span></div>

<div id="bookmarkshare">
<script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script>
<a class="addthis_button" href="http://www.addthis.com/bookmark.php?v=250&amp;username=khhong7"><img src="http://s7.addthis.com/static/btn/v2/lg-share-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"/></a><script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=khhong7"></script>
</div>


<img src="../images/cplusplus/cpp_logo.jpg" alt="cplusplus logo"/>

<div class="bodytext" style="padding: 12px;" align="justify"> 
<div class="subtitle_2nd" id="FullList">Full List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a> </li>
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors (Function Objects)</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="pointers.html">Pointers</a></li>
   <li><a href="pointers2.html">Pointers II</a></li>
   <li><a href="pointers3.html">Pointers III</a></li>
   <li><a href="assembly.html">Taste of Assembly</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL)</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="stl3_iterators.html">Standard Template Library (STL) III - Iterators</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="object_returning.html">Object Returning</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II - Native Thread for Win32 (A) </a></li>
   <li><a href="multithreaded2B.html">Multi-Threaded Programming II -  Native Thread for Win32 (B) </a></li>
   <li><a href="multithreaded2C.html">Multi-Threaded Programming II -  Native Thread for Win32 (C) </a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="embeddedSystemsProgramming.html">Embedded Systems Programming</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>
</ul>
</div>


<br />
<div class="bodytext" style="padding: 12px;" align="justify">
<div class="subtitle" id="memorydiagram">Memory Diagram</div>
<br />
<img src="images/assembly/memory_diagram_stack_heap.png" alt="memory_diagram_stack_heap"/>
<br />

<p>The picture above is the <strong>memory diagram</strong>, in which memory is
divided into several regions. Dynamically allocated memory created using the <strong>new/malloc</strong> operator
appears on the bottom of the diagram, which represents the region of memory
called the <strong>heap</strong>. Local variables declared as part of a procedure or function appear on the
top part of the diagram, which represents the <strong>stack</strong>.<br />
Modern architectures typically assign lower memory
addresses to addresses in the heap than they do to addresses the stack. </p>
<p>We have other regions in the diagram:<br />
<strong>Data</strong> region stores <strong>global/static</strong> variables and the compiled <strong>assembly</strong> resides in the <strong>Code </strong> segment.</p>
<br />
<br />


<div class="subtitle" id="stacks">Stack</div>
<p>Let's look at the following example and see how the local variables are set in the <strong>stack</strong> area:</p>
<pre>
void f1()
{
	int a;
	short b[4];
	double c;
	f2();
	f3();
}	
</pre>
<p>When we call f1() function, space needs to be set aside. The following picture shows <strong>activation records/stack frame</strong>:</p>
<img src="images/assembly/locals.png" alt="locals"/>
<br />
<p>When the function <strong>f1()</strong> is called, the <strong>stack pointer</strong> will be decremented by 20 bytes which is the size of the variables of <strong>f1()</strong>.</p>
<img src="images/assembly/stack_pointer.png" alt="stack_pointer"/>
<br />
<pre>
void f2()
{
	int x;
	char *y;
	char *z[2];
	f3();
}

void f3()
{
	double m[3];
	int n;
}
</pre>
<p>The following diagram shows the movement of <strong>stack pointer, sp</strong>: f1()->f1.f2()->f2.f3()->f2.f3() exits->f1.f2() exits.</p>
<img src="images/assembly/stack_pointer_f1_f2_f3.png" alt="stack_pointer_f1_f2_f3"/>
<p>After the f1.f2(), when we call f1.f3(), the variables of the function f3() simply overwrites them onto the area where the variables of f2() were.</p>
<br />
<br />


<div class="subtitle" id="mockassembly">Mock Assembly</div>
<p>This section introduces assembly, not the real one but the conceptual assembly just to learn how the stack is manipulated.</p>
<p>So, in this section, we're not going to use real names of registers such as Accumulator (EAX), Counter (ECX), Data (EDX), Base (EBX), Stack Pointer (ESP), Base Pointer (EBP), Source Index (ESI), and Destination Index (EDI) registers. But sometimes we may use Stack Pointer (ESP) or Instruction Pointer (EIP) registers, if necessary.</p>
<p>All the information in the code segment corresponds to the assembly code that was compiled to from our C/C++.</p>
<p>We're going to assume our processors have 32 of register set with 4-byte figure that has really fast access to. Registers themselves are electronically connected to the RAM. Every register draw/flush from/to RAM. </p>
<p>ALU does basic arithmetic (addition, subtraction, multiplication, division, shifting, and masking). In the picture, we're assuming that ALU is connected only to register not to RAM directly. That means that all the meaningful mathematical calculations have to actually be done in register. We have to take something from the memory and loaded into the register in order to add something to it. They can optimize just the load and store between register and RAM. So, any mathematical operations such as <strong>i++</strong> or <strong>i+1</strong> is to load the variables wherever they are either from heap or stack into registers and do the math and put the results into some other registers and flush them out to where belongs in memory.</p>
 
<img src="images/assembly/register_alu.png" alt="register_alu"/>
<br />
<p>Suppose we have:</p>
<pre>
i = 17;
j = 20;
j += i;
</pre>
<img src="images/assembly/AssemblyA.png" alt="AssemblyA"/>
<br />
<p>i = 17 is loaded into R1 and j = 10 is loaded into R2. j+i is compiles into assembly code. Assembly code is the recipe that knows how to load i and j into register set and do the addition and the flush the result back out to the same space that j occupies. What probably happen is that i will be loaded into R1 and j will be loaded into R2. We can add 17 to 20 and store result into R3 because R1 and R2 are connected to ALU which is capable of addition for us, and after we synthesize the result at R3. We can flush it back out to j. Note that the whole process is composed of 4 steps:</p>
<ul>
	<li>load i into register</li>
	<li>load j into register</li>
	<li>do the addition</li>
	<li>store the result into j </li>
</ul>
<p>Let's write the code in mock assembly for the following code:</p>
<pre>
int i;
int j;
i = 10;
j = i + 7;
j++;
</pre>
<p>The compiles into the following mock assembly:</p>
<pre>
// i = 10;
M[R1+4] = 10;	// store operation

// j = i + 1;
R2 = M[R1+4];	// load operation
R3 = R2 + 7;	// ALU operation
M[R1] = R3;	// store operation

// j++;
R2 = M[R1]	
R2 = R2 + 1;
M[R1] = R2;
</pre>
<img src="images/assembly/AssemblyB.png" alt="AssemblyB"/>
<br />
<p>R1 is the special dedicated register which stores the base address of the variables. M stands for the RAM and the value of 10 is stored 4 byte offset from the base address as M[R1+4] and then loaded into R2. After the addition of 7 at ALU, the result will be stored in the register R3 and flushed into the memory space with the base address.</p>
<p>Let's do an example that does not always deal with 4-byte quantities.</p>
<pre>
int i;
short s1;
short s2;
</pre>
<p>So, the activation record looks like this:</p>
<img src="images/assembly/short_activation_record.png" alt="short_activation_record"/>
<pre>
i = 200;	=>	[R1+4] = 200;
s1 = i;		=>	R2 = M[R1+4];
			M[R1+2] = <font color="red">.2</font> R2;	// .2 two-byte
s2 = s1 + 1;	=> 	R2 = <font color="red">.2</font> M[R1+1];
			R3 = R2 + 1;
			M[R1] = <font color="red">.2</font> R3;
</pre>
<br />
<img src="images/assembly/short_activation_record2.png" alt="short_activation_record2"/>
<br />
<img src="images/assembly/short_activation_record3.png" alt="short_activation_record3"/>
<br />
<br />
<img src="images/assembly/short_activation_record4.png" alt="short_activation_record4"/>
<br />
<br />
<br /><br />
<div class="subtitle_2nd" id="FullList">Full List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a> </li>
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="pointers.html">Pointers</a></li>
   <li><a href="pointers2.html">Pointers II</a></li>
   <li><a href="pointers3.html">Pointers III</a></li>
   <li><a href="assembly.html">Taste of Assembly</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL)</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="stl3_iterators.html">Standard Template Library (STL) III - Iterators</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="object_returning.html">Object Returning</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II - Native Thread for Win32 (A) </a></li>
   <li><a href="multithreaded2B.html">Multi-Threaded Programming II -  Native Thread for Win32 (B) </a></li>
   <li><a href="multithreaded2C.html">Multi-Threaded Programming II -  Native Thread for Win32 (C) </a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="embeddedSystemsProgramming.html">Embedded Systems Programming</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>
</ul>
<br /><br />


<br />


<br />
<br />
<br />


</div>
</div>
<div class="smallgraytext" id="footer"><a href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="#">Contact Us</a>
| Bogotobogo &copy; 2011 | <a target="_blank" href="http://www.bogotobogo.com">Bogotobogo </a>
</div>
</div>
</div>
</body>
</html>
